<template>
  <span v-if="showHot" class="card-search-point" @click="useSearchHttp(map)">热力图查询</span>
  <span v-else @click="cancelHot()">取消显示</span>
</template>

<script setup>
import { createDraw } from '../../../../../Hooks/useDraw'
import { Query } from '../../../../../Hooks/useQuery'
import { useGlobalMap } from '../../../../../plugins/globalmap'

const map = ref()
onMounted(() => {
  map.value = useGlobalMap()
})
let showHot = ref(true)
var hot_source = new ol.source.Vector({})
var hot_layer = new ol.layer.Vector({
  source: hot_source
})
const position = ref([])
let heatVector
let heatSource = new ol.source.Vector({})
const useSearchHttp = (map) => {
  showHot.value = false
  /* 创建画布 */
  map.addLayer(hot_layer)
  let draw
  draw = createDraw({
    type: 'Rectangle',
    source: hot_source
  })
  map.addInteraction(draw)

  draw.on('drawend', function (evt) {
    hot_source.clear()
    draw.setActive(false)
    /* 1、拉框查询获取几何信息 */
    var geometry = evt.feature.getGeometry()
    var service = {
      name: 'guanggu',
      layerId: 2
    }
    /* 2、根据几何信息调用中地接口,实现要素查询 */
    Query.queryByGeom({
      geometry,
      service,
      callback: handleQuery
    })
    map.removeInteraction(draw)
  })
  const handleQuery = (data) => {
    hot_source.clear()
    data.forEach((item) => {
      position.value.push(item.getGeometry().flatCoordinates)
    })

    //创建一个Heatmap图层
    position.value.forEach((item) => {
      var point = new ol.Feature({
        geometry: new ol.geom.Point(item)
      })
      heatSource.addFeature(point)
      heatVector = new ol.layer.Heatmap({
        //矢量数据源
        source: heatSource,
        //热点半径
        radius: 25,
        //模糊尺寸
        blur: 10
      })
    })
    map.addLayer(heatVector)
  }
}

function cancelHot() {
  position.value = []
  showHot.value = true
  hot_source.clear()
  heatSource.clear()
  map.value.removeLayer(map.value.getLayers().item(2))
}
</script>

<style lang="less" scoped></style>
